package com.keter.checker.service;

import com.keter.checker.model.Target;
import com.keter.checker.util.OKHttpUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by gulx@neusoft.com on 2019/5/24.
 */
@Component
public class CheckerService {
    private static final Logger logger = LoggerFactory.getLogger(CheckerService.class);

    @Autowired
    OKHttpUtil httpUtil;

    @Value("${targets.contentLength}")
    private int length;

    Map<Integer, Target> results;

    public Map<Integer, Target> check(String[] url) {
        results = new TreeMap<>();
        for (int i = 0; i < url.length; i++) {
            logger.info("checking url {}:{}", i, url[i]);
            get(url[i], i);
        }
        while (results.size() < url.length) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                logger.error("", e);
            }
        }
        return results;
    }

    private void get(String url, int index) {
        Target target = new Target();
        target.setUrl(url);
        Request request = new Request.Builder().url(url).build();
        long before = System.currentTimeMillis();
        httpUtil
                .client()
                .newCall(request)
                .enqueue(
                        new Callback() {
                            @Override
                            public void onResponse(Call call, final Response response) throws IOException {
                                final String res = response.body().string();
                                final boolean ok = response.isSuccessful();
                                Target target = new Target();
                                target.setUrl(url);
                                if (ok) {
                                    // 内容截断
//                if (res.length() >= length) {
//                  target.setRes("("+res.substring(0, length).concat("...").replace("\n"," ")+")");
//                } else {
//                  target.setRes(res);
//                }
                                    target.setTime(System.currentTimeMillis() - before);
                                    target.setStatus("OK");
                                    logger.info("res:{}", target);
                                } else {
                                    logger.warn("WARN: {} 响应状态:{}",url, response.code());
                                    target.setStatus("WARN");
                                    target.setError("code:" + response.code());
                                }
                                results.put(index , target);
                            }

                            @Override
                            public void onFailure(Call call, IOException e) {
                                target.setTime(System.currentTimeMillis() - before);
                                target.setStatus("ERROR");
                                logger.error("url:{} 调用异常！原因：{}", call.request().url(), e.getMessage());
//                                logger.error("", e);
//                target.setRes(e.getMessage().replace("\n"," "));
                                results.put(index, target);
                                target.setError(e.getMessage());

                            }
                        });
    }
}
